<template>
	<view class="my-shop-add-wp">
		<view class="my-shop-add-form">
			<u--form errorType="message" labelPosition="top" :model="model" :rules="rules" ref="form" labelWidth='180'
				labelAlign='left' :labelStyle="{fontSize: '26rpx',color: '#1D2129',height:'80rpx',lineHeight:'80rpx'}"
				:borderBottom="true">
				<u-form-item label="商品名称" prop="prodName" borderBottom class='formItemWp' required>
					<u--input placeholder="请输入商品名称(20字内)" maxlength="20" suffixIconStyle="color: #909399;font-size:30rpx"
						border="none" v-model="model.prodName" clearable>
					</u--input>
				</u-form-item>
				<u-form-item label="商品价格" borderBottom class='formItemWp'>
					<u--input placeholder="请输入商品价格(8位内)" maxlength="8" suffixIconStyle="color: #909399;font-size:30rpx"
						border="none" v-model="model.price" clearable>
					</u--input>
				</u-form-item>
				<u-form-item label="商品单位" prop="units" borderBottom class='formItemWp' required>
					<u--input placeholder="请输入商品单位(8字内)" maxlength="8" suffixIconStyle="color: #909399;font-size:30rpx"
						border="none" v-model="model.units" clearable>
					</u--input>
				</u-form-item>
				<u-form-item labelWidth='614' labelPosition="left" label="是否允许使用代金券" prop="" borderBottom class='formItemWp'>
					<u-switch size="30" v-model="model.voucher" :activeValue="1" :inactiveValue="0"></u-switch>
				</u-form-item>
				<u-form-item label="商品封面" borderBottom class='formItemWp' required>
					<view @click="choosePicImg">
						<view v-if="cropperPic">
							<u-image :src="cropperPic" width="218rpx" height="218rpx" mode="widthFix"></u-image>
						</view>
						<view class="uploadWp" v-else>
							<u-icon name="plus" color="#c9cdd4" size="60"></u-icon>
							<text style="color: #c9cdd4;font-size: 24rpx;">点击上传</text>
						</view>

					</view>
				</u-form-item>
				<u-form-item label="商品简介" borderBottom class='formItemWp'>
					<textarea v-model='model.brief' @blur="bindTextAreaBlur" :maxlength="500" placeholder="请输入商品简介(500字内)"
						style="background:#fff;width: 100%; padding: 20rpx 0;" />
				</u-form-item>
				<u-form-item label="商品详情" borderBottom class='formItemWp  formImgWp'>
					<u-upload accept="image" :fileList="fileListImgs" @afterRead="afterRead" @delete="deletePic" name="Imgs"
						:multiple='true' :maxCount="10" width="200" height="200" imageMode="aspectFit">
						<view class="uploadWp">
							<u-icon name="plus" color="#c9cdd4" size="60"></u-icon>
							<text style="color: #c9cdd4;font-size: 24rpx;">点击上传</text>
						</view>
					</u-upload>
				</u-form-item>
				<u-form-item labelPosition="left" label="线上支付" prop="" borderBottom class='formItemWp'>
					<div style="display: flex;margin-left: auto;">
						<u-switch size="30" v-model="model.onlinePay" :activeValue="1" :inactiveValue="0"></u-switch>
					</div>
				</u-form-item>
			</u--form>
		</view>
		<view class="btn-box">
			<u-button v-if="isSubmitDirectly" :throttleTime="800" @click.stop.prevent="submit" :custom-style="{
				  background: '#276aee',
				  color: '#fff',
				  width: '682rpx',
				  border:'none'
				}">提交</u-button>
			<u-button v-else :throttleTime="800" @click.stop.prevent="goToAddPayInfo" :custom-style="{
				  background: '#276aee',
				  color: '#fff',
				  width: '682rpx',
				  border:'none'
				}">下一步 设置支付信息</u-button>

		</view>
		<ksp-cropper mode="fixed" :width="300" :height="300" :maxWidth="1024" :maxHeight="1024" :url="cropperUrl"
			@cancel="cropperUrl=''" @ok="cropperOk"></ksp-cropper>
	</view>


</template>

<script>
	import kspCropper from '@/components/ksp-cropper/ksp-cropper.vue'
	import {
		mapState,
		mapGetters
	} from 'vuex'
	import baseConfig from '@/config/baseUrl.js'
	export default {
		data() {
			return {
				model: {
					prodName: '',
					units: '',
					price: '',
				},
				cropperUrl: '',
				cropperPic: '',
				goodsId: '',
				fileListImgs: [], //详情图
				rules: {
					prodName: [{
						required: true,
						message: '请输入商品名称',
						trigger: 'blur'
					}],
					units: [{
						required: true,
						message: '请输入商品单位',
						trigger: 'blur',
					}]

				},
				hasPayInfo: false
			}
		},
		onShow() {
			this.checkPayInfo()
		},
		onReady() {
			this.$refs.form.setRules(this.rules)
		},
		onLoad(opt) {
			if (opt.id) {
				this.goodsId = opt.id
				this.getGoodsInfo()
			}
		},
		computed: {
			...mapGetters(['userInfo']),
			isSubmitDirectly() {
				return this.hasPayInfo ? true : !this.model.onlinePay
			}
		},
		methods: {
			async checkPayInfo() {
				const {
					openId
				} = this.userInfo
				let res = await this.$api.verifyExist({
					openId
				})
				if (res.success && res.code == 200) {
					this.hasPayInfo = res.result
				}
			},
			goToAddPayInfo() {
				uni.$u.route('/pagesMall/myShop/addPayInfo', {
					addPayInfo: 1
				});
			},
			async getGoodsInfo() {
				const {
					openId
				} = this.userInfo
				let res = await this.$api.getProdShopDetail({
					id: this.goodsId,
					openId
				})
				if (res.success && res.result) {
					console.log(res.result);
					this.model = res.result
					let fileListImgs = []
					//处理主图
					this.cropperPic = this.model.pic
					//处理详情图
					if (this.model.images && this.model.images.length > 0) {
						//只有一张图片
						if (this.model.images.indexOf(',') == -1) {
							fileListImgs.splice(0, 1, this.model.images)
						} else {
							//多张图片
							fileListImgs = this.model.images.split(',')
						}
						this.fileListImgs = fileListImgs.map(item => {
							if (item.length > 1) {
								let newItem = {
									url: item,
									filePath: item
								}
								return newItem
							}
						})
					} else {
						this.fileListImg = []
					}
				} else {
					this.model = {}
					uni.showToast({
						icon: 'none',
						title: res.message
					})
				}
			},
			choosePicImg(e) {
				console.log(e);
				uni.chooseMedia({
					count: 1,
					mediaType: ['image'],
					success: (rst) => {
						// 设置url的值，显示控件
						console.log(rst, 'rst');
						this.cropperUrl = rst.tempFiles[0].tempFilePath;
					}
				});
			},
			async cropperOk(ev) {
				this.cropperUrl = "";
				//上传
				this.cropperPic = await this.uploadFilePromise(ev.path)
				console.log(this.cropperPic, '裁剪-上传后路径');
			},
			bindTextAreaBlur(e) {
				if (!e.detail.value) {
					return uni.showToast({
						title: '请输入商品简介',
						icon: 'none'
					});
				}
				this.model.brief = e.detail.value
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				console.log('新增图片', event);
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: event.name,
						url: result,
						fileName: event.file[0].type + event.file[0].size + '',
						filePath: result
					}))
					fileListLen++
				}

			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: baseConfig.uploadUrl + '/casugn-system/sys/common/upload',
						filePath: url,
						name: 'file',
						success: (res) => {
							let data = JSON.parse(res.data)
							if (data.success) {
								resolve(data.message)
							}
						}
					});
				})
			},
			submit() {
				let fileListImgs = this.fileListImgs.map(item => item.url)
				fileListImgs = fileListImgs.join()
				if (!this.cropperPic) {
					return uni.showToast({
						icon: 'none',
						title: '请上传商品封面'
					})
				}
				// if (this.model.price == '' || !this.model.price) {
				// 	return uni.showToast({
				// 		icon: 'none',
				// 		title: '请填写商品价格'
				// 	})
				// }
				const {
					openId
				} = this.userInfo
				this.$refs.form.validate().then(async res => {
					let payload = {
						...this.model,
						pic: this.cropperPic,
						images: fileListImgs,
						openId,

					}
					const {
						success,
						message
					} = await this.$api.editMyGoods(payload)
					if (success) {
						uni.showToast({
							title: '修改成功'
						})
						setTimeout(() => {
							uni.navigateBack()
						}, 2000)

					} else {
						uni.showToast({
							title: '修改失败',
							icon: 'none'
						});
					}
				}).catch(errors => {
					uni.$u.toast('请补充完整所需项')
				})

			},

		}
	}
</script>


<style lang="scss" scoped>
	::v-deep .u-upload .uicon-close {
		font-size: 24rpx !important;
		top: 6rpx !important;
	}

	.my-shop-add-wp {
		padding-bottom: 200rpx;

		.my-shop-add-form {
			margin: 32rpx;



			.uploadWp {
				width: 218rpx;
				height: 218rpx;
				background-color: #f7f8fa;
				justify-content: center;
				display: flex;
				flex-direction: column;
				align-items: center;
				text-align: center;
			}
		}

		.btn-box {
			width: 100%;
			display: flex;
			justify-content: center;
			align-items: center;
			flex-direction: column;
			border: none;
			position: fixed;
			bottom: 20rpx;
			bottom: calc(constant(safe-area-inset-bottom) + 20rpx);
			bottom: calc(env(safe-area-inset-bottom) + 20rpx);
			z-index: 999;
		}
	}
</style>